<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-form-item label="终端号" prop="vehicleId">
            <el-input v-model="queryParams.code" placeholder="请输入终端号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="车牌号" prop="code">
            <el-select v-model="queryParams.vehicleId" filterable>
              <el-option v-for="option in vehicleList" :key="option.id" :value="option.id"
                :label="option.plateNo + '(' + option.numbered + ')'" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="部门" prop="deptId">
            <el-tree-select v-model="queryParams.deptId" @keyup.enter="handleQuery" :data="deptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门"
              check-strictly clearable filterable />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option v-for="dict in sys_data_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['basic:device:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['basic:device:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleImport"
          v-hasPermi="['basic:sim:import']">导入数据</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" border stripe :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column label="车牌号" align="center" prop="vehiclePlatNo" width="100" />
      <el-table-column label="终端号" width="120" align="left" prop="code" />
      <el-table-column label="MSISDN / SIM卡号" width="150" align="left" prop="msisdn" />
      <el-table-column label="设备协议" width="100" align="left" prop="protocol">
        <template #default="scope">
          <dict-tag :options="basic_device_protocol" :value="scope.row.protocol" />
        </template>
      </el-table-column>
      <el-table-column label="调度协议" align="left" prop="dispatchProtocol">
        <template #default="scope">
          <dict-tag :options="basic_device_dispatch_protocol" :value="scope.row.dispatchProtocol" />
        </template>
      </el-table-column>
      <el-table-column label="部门" align="left" prop="deptName" :show-overflow-tooltip="true" />
      <el-table-column label="状态" width="80" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_data_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="终端产商" align="left" prop="productName" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :options="basic_device_product" :value="scope.row.productName" />
        </template>
      </el-table-column>
      <el-table-column label="厂商设备型号" align="left" prop="productModel" />
      <el-table-column label="出厂日期" width="100" align="center" prop="productDate" />
      <el-table-column label="版本号" width="120" align="left" prop="versions" />
      <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['basic:device:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['basic:device:remove']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改设备终端对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="deviceRef" :model="form" :rules="rules" label-width="130px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="车牌号" prop="vehicleId">
              <el-select v-model="form.vehicleId" filterable>
                <el-option v-for="option in vehicleList" :key="option.id" :value="option.id"
                  :label="option.plateNo + '(' + option.numbered + ')'" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="终端号" prop="code">
              <el-input v-model="form.code" placeholder="请输入终端号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="设备协议" prop="protocol">
              <el-select v-model="form.protocol" placeholder="请选择状态" clearable>
                <el-option v-for="item in basic_device_protocol" :label="item.label" :value="item.value"
                  :key="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调度协议" prop="dispatchProtocol">
              <el-select v-model="form.dispatchProtocol" placeholder="请选择状态" clearable>
                <el-option v-for="item in basic_device_dispatch_protocol" :label="item.label" :value="item.value"
                  :key="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status">
                <el-option v-for="dict in sys_data_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-tree-select v-model="form.deptId" :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门"
                check-strictly clearable filterable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="终端产商" prop="productName">
              <el-select v-model="form.productName" placeholder="请选择终端产商" clearable>
                <el-option v-for="item in basic_device_product" :label="item.label" :value="item.value"
                  :key="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厂商设备" prop="productNumber">
              <el-input v-model="form.productNumber" placeholder="请输入厂商设备" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="厂商设备型号" prop="productModel">
              <el-input v-model="form.productModel" placeholder="请输入厂商设备型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出厂日期" prop="productDate">
              <el-date-picker clearable v-model="form.productDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择出厂日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="PN" prop="pn">
              <el-input v-model="form.pn" placeholder="请输入PN" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="IMEI号" prop="imei">
              <el-input v-model="form.imei" placeholder="请输入IMEI号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="IMSI号" prop="imsi">
              <el-input v-model="form.ismi" placeholder="请输入IMSI号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="MSISDN/SIM卡号" prop="imsi">
              <el-select v-model="form.msisdn">
                <el-option v-for="option in simList" :key="option.msisdn" :value="option.msisdn" :label="option.msisdn" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="视频通道数量" prop="imsi">
              <el-input v-model="form.videoChannel" placeholder="请输入视频通道数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="音频通道数量" prop="imsi">
              <el-input v-model="form.audioChannel" placeholder="请输入音频通道数量" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" action="#" :http-request="httpRequest"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag :data="upload.form">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <el-form :model="upload.form" ref="uploadForm" label-width="100px">
              <el-form-item label="部门" :rules="{ required: true, message: '部门不能为空', trigger: 'change' }" prop="deptId">
                <el-tree-select v-model="upload.form.deptId" :data="deptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门"
                  check-strictly filterable />
              </el-form-item>
            </el-form>
            <br />
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
              @click="handleTemplateImport">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Device">
import BasicTable from '@/components/BasicTable/BasicTable.vue'
import { getToken } from "@/utils/auth"
import { deptTreeSelect } from "@/api/system/user";
import { listVehicle } from "@/api/basic/vehicle";
import { listSim } from "@/api/basic/sim";
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from "@/api/basic/device";
import { ref } from 'vue';
const { proxy } = getCurrentInstance();
const { sys_data_status } = proxy.useDict('sys_data_status');
const { basic_device_protocol } = proxy.useDict('basic_device_protocol');
const { basic_device_dispatch_protocol, basic_device_product } = proxy.useDict('basic_device_dispatch_protocol', 'basic_device_product');

const deviceList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
/** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  form: {
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    deptId: undefined,
  },
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: "basic/device/import/data"
})

const deptOptions = ref([])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    vehicleId: undefined,
    code: undefined,
    protocol: undefined,
    dispatchProtocol: undefined,
    status: undefined,
    deptId: undefined,
    productName: undefined,
    productNumber: undefined,
    productModel: undefined,
    productDate: undefined,
    pn: undefined,
    imei: undefined,
    imsi: undefined,
    installTime: undefined,
    versions: undefined,
    videoChannel: undefined,
    audioChannel: undefined,
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    code: [
      { required: true, message: "终端号不能为空", trigger: "blur" }
    ],
    protocol: [
      { required: true, validator: validateDispatchProtocol, trigger: "blur" }
    ],
    dispatchProtocol: [
      { required: true, validator: validateDispatchProtocol, trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    deptId: [
      { required: true, message: "部门ID不能为空", trigger: "blur" }
    ],
    productName: [
      { required: true, message: "终端产商不能为空", trigger: "blur" }
    ],
    productNumber: [
      { required: true, message: "厂商设备ID不能为空", trigger: "blur" }
    ],
    productDate: [
      { required: true, message: "出厂日期不能为空", trigger: "blur" }
    ],
  }
});

function validateDispatchProtocol(rule, value, callback) {
  if (!form.value.protocol && !form.value.dispatchProtocol) {
    callback(new Error('设备协议，调度协议至少选填一样'))
  } else {
    callback()
  }
}
const { queryParams, form, rules } = toRefs(data);

/** 查询设备终端列表 */
function getList() {
  loading.value = true;
  listDevice(queryParams.value).then(response => {
    deviceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
const vehicleList = ref()
/** 查询车辆列表 */
function getlistVehicle() {
  loading.value = true;
  listVehicle().then(response => {
    vehicleList.value = response.rows;
  });
}
getlistVehicle()
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
const simList = ref()
/** 查询SIM卡号列表 */
function getListSim() {
  loading.value = true;
  listSim(queryParams.value).then(response => {
    simList.value = response.rows;
  });
}
getListSim()
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
/** 导入按钮操作 */
function handleImport() {
  upload.title = '设备终端导入';
  upload.open = true;
}
/** 获取导入模板按钮操作 */
function handleTemplateImport() {
  proxy.download('/basic/device/import/template', {}, `设备终端导入模板.xlsx`)
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
  upload.open = false
  getList()
};
/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
function httpRequest(data) {
  // 封装FormData对象
  data.data[data.filename] = data.file
  upload.open = false;
  upload.isUploading = false;
  proxy.importFile(upload.url, data.data).then(res => {
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + res.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  }).catch(err => {
    proxy.$refs["uploadRef"].handleRemove(data.file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + err + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
  })
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    vehicleId: null,
    code: null,
    protocol: null,
    dispatchProtocol: null,
    status: null,
    deptId: deptOptions.value[0].id,
    productName: basic_device_product.value[0].value,
    productNumber: null,
    productModel: null,
    productDate: null,
    pn: null,
    imei: null,
    imsi: null,
    installTime: null,
    versions: null,
    videoChannel: null,
    audioChannel: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("deviceRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备终端";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getDevice(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改设备终端";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deviceRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备终端编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delDevice(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('basic/device/export', {
    ...queryParams.value
  }, `device_${new Date().getTime()}.xlsx`)
}

getDeptTree();
getList();
</script>

<style scoped>
.el-form--inline .el-form-item {
  margin-right: 28px;
}
</style>